package cn.etg.core;

import cn.etg.annotation.Controller;
import cn.etg.annotation.RequestMapping;
import cn.etg.controller.UserController;
import cn.etg.http.HttpServletRequest;
import cn.etg.http.HttpServletResponse;

import java.io.File;
import java.io.FileFilter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URISyntaxException;

public class DispatcherServlet {
    // 1 创建静态变量 DispatcherServlet
    private static  DispatcherServlet instance= new DispatcherServlet();

    private static File baseDir;
    private static File staticDir;

    // 2创建私有构造
    private DispatcherServlet(){}

    // 3创建方法实现实例化
    public static DispatcherServlet getInstance(){
        return instance;
    }
    static{
        try {
            baseDir = new File(
                    DispatcherServlet.class.getClassLoader()
                            .getResource(".")
                            .toURI());
            // 定位static文件夹
            staticDir = new File(baseDir,"static");
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
    }
    public void service(HttpServletRequest request,HttpServletResponse response) throws URISyntaxException {
        // 获得抽象路径
        String uriPath = request.getRequestURI();
        // 输出抽象路径
        System.out.println(uriPath);
        Method method = HandlerMapping.getMethod(uriPath);
        if(method!=null){
            try {
                Class<?> cls = method.getDeclaringClass();
                Object o = cls.newInstance();
                method.invoke(o,request,response);
            } catch (Exception e) {
                e.printStackTrace();
                // 500异常
                response.setStatusCode(500);
                response.setStatusReason("Internal Server Error");
                response.setContentFile(new File(staticDir,"500.html"));
            }


        }else {
            // 通过请求获取的抽象路径，定位浏览器实际请求的static下的资源
            File file = new File(staticDir,uriPath);
            System.err.println();
            if(file.exists() && file.isFile()){
                response.setContentFile(file);
            }else{
                response.setStatusCode(404);
                response.setStatusReason("NotFound");
                file=new File(staticDir,"404.html");
                response.setContentFile(file);
            }
        }





    }
}
